// 导入 Vue 的响应式 API，包括 ref 和 computed
import {ref, computed} from 'vue'
// 导入 Pinia 的 defineStore 方法，用于定义状态管理 store
import {defineStore} from 'pinia'
// 导入封装的请求模块，用于发送 HTTP 请求
import request from '@/utils/request'
// 导入 User 类型定义，用于类型检查
import type {User, ApiResponse} from '@/types/user'
// 导入路由实例，用于重定向
import router from '@/router'

interface LoginForm {
    username: string  // 用户名
    password: string // 密码
}

interface RegisterForm {
    username: string
    password: string
    email?: string // 邮箱, 可选
    phonenumber?: string // 手机号, 可选
}

export const useUserStore = defineStore('user', () => {
    // 状态
    // 用户信息响应式变量，初始值为null
    const user = ref<User | null>(null)
    // 认证令牌响应式变量，从localStorage中获取初始值
    const token = ref<string | null>(localStorage.getItem('token'))
    // 计算属性，用于判断用户是否已登录（基于token是否存在）
    const isLoggedIn = computed(() => !!token.value)
    // 计算属性，用于判断用户是否已完全认证（既有token又有用户信息）
    const isAuthenticated = computed(() => !!token.value && !!user.value)

    // 登录
    // const login = async (loginForm: LoginForm) => {
    //     try {
    //         const response = await request.post('/api/user/login/', loginForm) as ApiResponse<{token: string, user: User}>
    //         if (response.code === 200 && response.data) {
    //             const {token: jwtToken, user: userInfo} = response.data
    //             token.value = jwtToken
    //             user.value = userInfo
    //             localStorage.setItem('token', jwtToken)
    //
    //             return {success: true, message: response.message}
    //         } else {
    //             return {success: false, message: response.message}
    //         }
    //     } catch (error: any) {
    //         return {
    //             success: false,
    //             message: error.message || '登录失败，请稍后重试'
    //         }
    //     }
    // }

    // 登录
    const login = async (loginForm: LoginForm) => {
        try {

            const response = await request.post('/api/user/login/', loginForm);
            const apiResponse = response.data as ApiResponse<{ token: string, user: User }>;
            if (apiResponse.code === 200 && apiResponse.data) {
                const {token: jwtToken, user: userInfo} = apiResponse.data;
                token.value = jwtToken;
                user.value = userInfo;
                localStorage.setItem('token', jwtToken);

                return {success: true, message: apiResponse.message};
            } else {
                return {success: false, message: apiResponse.message};
            }
        } catch (error: any) {
            return {
                success: false,
                message: error.message || '登录失败，请稍后重试'
            };
        }
    };


    // 恢复登录状态
    const restoreLoginState = async () => {
        const savedToken = localStorage.getItem('token')
        if (savedToken) {
            try {
                token.value = savedToken
                // 尝试获取用户信息验证token有效性
                if (!user.value) {
                    await fetchUserInfo()
                }
                console.log('恢复登录状态成功')
                return true
            } catch (error: any) {
                console.error('恢复登录状态失败:', error)
                // 只在401认证失败时清除token，其他错误保留token
                if (error?.response?.status === 401) {
                    console.log('认证失败，清除认证信息')
                    clearAuth()
                    throw error
                } else {
                    // 网络错误或其他临时错误，保留token允许用户重试
                    console.log('网络错误或临时错误，保留token')
                    return false
                }
            }
        }
        return false
    }

    /**
     * 用户注册函数
     * @param registerForm - 注册表单数据，包含用户注册所需的信息
     * @returns Promise对象，包含注册结果信息，格式为{success: boolean, message: string}
     */
    const register = async (registerForm: RegisterForm) => {
        try {
            console.log("registerForm:", registerForm)
            // 发送注册请求到服务器
            // const response = await request.post('/user/register/', registerForm) as ApiResponse
            const response = await request.post('/api/user/register/', registerForm)
            const apiResponse = response.data as ApiResponse
            // 根据服务器返回的状态码判断注册是否成功
            if (apiResponse.code === 200) {
                console.log("response:", apiResponse)
                return {success: true, message: apiResponse.message}
            } else {
                console.log("response:", apiResponse)
                return {success: false, message: apiResponse.message}
            }
        } catch (error: any) {
            console.log("response_error:", error)
            // 处理注册过程中出现的异常情况
            return {
                success: false,
                message: error.message || '注册失败，请稍后重试'
            }
        }
    }

    // 登出
    const logout = () => {
        if (token.value) {
            localStorage.removeItem('token')
            user.value = null
            token.value = null
            router.push('/login')
        }
    }

    // 获取用户信息（用于token验证）
    const fetchUserInfo = async () => {
        try {


            const response = await request.get('/api/user/info/')
            const apiResponse = response.data as ApiResponse<User>

            console.log('获取用户信息response:', apiResponse)
            if (apiResponse.code === 200 && apiResponse.data) {
                user.value = apiResponse.data
                return apiResponse.data
            } else {
                throw new Error(apiResponse.message || '获取用户信息失败')
            }
        } catch (error: any) {
            console.error('获取用户信息失败:', error)
            throw error
        }
    }

    // 清除认证信息
    const clearAuth = () => {
        localStorage.removeItem('token')
        user.value = null
        token.value = null
    }

    return {
        user,
        token,
        isLoggedIn,
        isAuthenticated,
        login,
        register,
        logout,
        fetchUserInfo,
        clearAuth,
        restoreLoginState,
    }
})
